// pages/select/select.js
var util = require('../../utils/util.js')
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //-----------------------------------------------【悬浮按钮】参数
    showOperationButtons: false,
    animationData: {},
    opacityAnimation: {},
    //-----------------------------------------------【产品管理首页】参数
    allProductData: null, //酸奶产品数据
    navActiveId: 0, //导航栏激活id
    showDetail: false, //是否显示商品详情
    detailInfo: undefined, //商品详情信息
    optionData: undefined, //商品选项区域数据
    showOption: false, //显示商品选择窗体 
    initialPrice: 0, //选项列表中的产品初始价格
    optionDescrib: '', //已选加料说明
    currentPrice: 0, //选项列表中的实时价格
    cartListData: [], //购物车列表数据
    currentAdditions: [],//当前选项界面所选小料列表
    currentDiscount: 0,//当前所选产品的优惠价格
    scrollType: '点击导航',//定义滚动类型,
    //********更改产品类别参数*******/
    showClassOptions: false,//是否显示产品类别更改窗体
    currentProductIndex: '',//当前操作的产品index（yoghourt数组中的index）
    selectedClassTypeName: '', //已选的类别名称
    //********编辑产品信息参数*******/
    showDeleteMask: false,
    showProductDetailInfo: false, //显示产品信息
    showChooseOptionsType: false,//显示加料选项选择窗口
    optionsIdArr:[], //加料类别选择数组
    currentProductInfo: {//当前所选产品信息
      id: '',
      name: '',
      price: '',
      promotionprice: '',
      salenum: '',
      intro: '',
      label: [],
      optiontypeid: '',
      bigimage: '',
      smallimage: '',
      typeid: '',
      visible: ''
    },
    //--------------------------------------------------【类别管理窗口】参数
    showManageClassForm: false, //控制显示类别管理窗口
    tempProductData1: '',//用来临时存储产品数据
    classInfo: {    //类别信息
      id: '',
      index: '',
      typename: '',
      description: '',
      image: ''
    },
    classNavActiveId: null, //产品类别导航栏激活id
    unclassifyProduct: [], //未分类产品暂存
    //--------------------------------------------------【加料管理窗口】参数
    optionsInfo: '', //加料选项数据
    optionsInfoCopy: '',//加料选项数据副本（用于直接操作）
    showManageOptionsForm: false, //控制是否显示：加料管理页面  
    optionsNavActiveId: 0, // 导航栏所选index
    showLabelOperationButtons:false //长按显示标签操作按钮
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //*********************************
    //加载此页面时，将内存中的产品信息，加载到本页的变量中
    let that = this
    wx.showLoading({title:'正在加载数据'})
    // *********************************  刷新产品信息
    var app_data = getApp().globalData;
    //-----1. 清空本地产品数据
    try {
      app_data.productInfo = null
      app_data.optionsInfo = null
    } catch (e) { }
    //-----2. 从数据库重新获取产品数据
    // setTimeout(function () {
    wx.cloud.callFunction({
      name: 'getData'
    })
      .then(function (res) {
        //将读取的产品信息数据，赋值给全局变量
        app_data.productInfo = res.result.productInfo
        app_data.optionsInfo = res.result.optionsInfo
      })
      .catch(function (res) {
        this.show_famulei_loading(false)
        wx.showModal({
          title: '加载失败',
          content: '请检查您的网络',
          showCancel: false,
        })
      })
    // }, 4000, app_data)
    // ********************************* 定时器 检测产品数据是否获取完成
    let time = 0
    let check_clock = setInterval(() => {
      time = time + 100
      // console.log("计时器:" + time + "ms")
      if (app_data.productInfo !== null) {
        wx.hideLoading()
        // 将最新的产品数据同步
        that.setData({
          allProductData: app_data.productInfo,
          optionsInfoCopy: app_data.optionsInfo,
          optionsInfo: app_data.optionsInfo
        })
        //*********************************关闭计时器
        clearInterval(check_clock)
      } else if (time > 5000) {
        wx.hideLoading()
        clearInterval(check_clock)
        wx.showModal({
          title: '网络故障',
          content: '无法加载产品数据，请检查您的网络',
          showCancel: false,
          confirmText: '我知道了',
          complete: function (res) {
            if (res.confirm) {
              wx.navigateBack()
            }
          }
        })
      }
    }, 100, check_clock, time)
  },
  //---------------------------------导航栏点击事件
  navClick: function (e) {
    var temp = e.currentTarget.dataset.id;
    this.setData({
      navActiveId: temp
    })
  },
  //---------------------------------打开商品展示详情
  openDetail: function (e) {
    var info = e.currentTarget.dataset.info

    this.setData({
      detailInfo: info,
      showDetail: true

    })
  },
  //---------------------------------关闭商品展示详情
  closeDetail: function (e) {
    this.setData({
      showDetail: false
    })
  },
  consoleLogHello: function () {
    console.log('hello!');
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
    var opacity = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animationOpacity = opacity
  },
  //----------------------------------------显示产品可选项
  openOption: function (e) {
    var optionsInfo = this.data.optionsInfo //获取内存中的选项信息
    //console.log(optionsInfo)
    var info = e.currentTarget.dataset.info;
    //获取商品的实际销售价格
    var initialPrice = 0;
    var discount = 0;
    if (info.promotionprice == 0) {
      //(1)所选商品没有优惠价格
      initialPrice = info.price;
    } else {
      //(2)所选商品有优惠价格
      initialPrice = info.promotionprice;
      discount = info.price - info.promotionprice;
    }
    var typeid = info.optiontypeid;
    var optionData = Array();

    for (var i = 0; i < optionsInfo.length; i++) {
      if (optionsInfo[i].id == typeid) {
        optionData = optionsInfo[i].optionData;
        break;
      }
    }
    this.setData({
      showDetail: false, //设置选项窗体可见
      showOption: true, //设置选项窗体可见
      detailInfo: info, //传输产品信息至此窗体
      optionData: optionData,
      initialPrice: initialPrice, //选项列表中的价格
      currentPrice: initialPrice, //当前所选产品价格
      currentDiscount: discount, //当前所选产品的折扣价格
      optionDescrib: '', //已选加料说明
    })
  },
  //------------------------------点击按钮选项事件
  optionClick: function (e) {
    var selected = e.currentTarget.dataset.selected;
    var price = e.currentTarget.dataset.price;
    var listid = e.currentTarget.dataset.listid;
    var optionData = this.data.optionData;
    if (selected == 0) //由未标记---变为已标记
    {
      selected = 1
      wx.showToast({
        image: '../../images/coin.png',
        title: '+' + price,
        duration: 500
      })
    } else //由已标记---变为未标记
    {
      selected = 0
      wx.showToast({
        image: '../../images/coin_sub.png',
        title: '-' + price,
        duration: 400
      })
    }
    //---------------------------通过循环刷新点击样式、已选加料、价格
    var label = '';
    var addPrice = 0;
    var additions = []; //定义一个空数组，用来存放小料加价说明
    var initialPrice = Number(this.data.initialPrice);
    for (var i = 0; i < optionData.length; i++) {
      var temp = optionData[i].optionlistData;
      for (var j = 0; j < temp.length; j++) {
        if (temp[j].listid == listid) {
          temp[j].selected = selected;
        }
        if (temp[j].selected == 1) //如果选中状态
        {
          label += temp[j].name + '+'
          addPrice += Number(temp[j].price)
          additions.push({ "addName": temp[j].name, "addPrice": Number(temp[j].price) })
        }
      }
    }
    console.log(additions)
    //--------------------------------------
    this.setData({
      optionData: optionData,
      currentPrice: initialPrice + addPrice, //选项列表中的价格
      optionDescrib: label.substring(0, label.length - 1), //已选加料说明
      currentAdditions: additions //将当前所选加料记录成列表
    })
  },
  //----------------------------------------关闭产品可选项
  closeOption: function (e) {
    this.setData({
      showOption: false
    })
  },
  //**************************************【主页设置按钮】相关事件***************************************** */

  //点击首页更多设置，展开
  moreSettingsClick: function () {
    let that = this
    let openSettings = this.data.showOperationButtons;
    if (!openSettings) //处于关闭状态
    {
      this.rotate(180);
      this.setData({
        showOperationButtons: true
      })
      this.opacity(0, 1)
    } else {
      this.rotate(-180);
      this.opacity(1, 0)
      setTimeout(function () {
        that.setData({
          showOperationButtons: false
        })
      }, 1000)
    }
  },
  // 旋转[-180, 180]
  rotate: function (angle) {
    this.animation.rotate(angle).step({ duration: 1500 })
    this.setData({
      animationData: this.animation.export()
    })
  },
  // 设置透明度[0, 1]
  opacity: function (start, end) {
    this.animationOpacity.opacity(start).opacity(end).step({ duration: 1000 })
    this.setData({
      opacityAnimation: this.animationOpacity.export()
    })
  },
  //**************************************【类别管理】相关事件******************************************* */
  //点击【类别管理】：显示类别管理窗口
  showManageClassForm: function (e) {
    let tempProductData1 = this.data.allProductData
    //首次进入类别管理界面，默认选中第一个tab
    let classInfo = {    //类别信息
      id: tempProductData1[0].id,
      index: 0,
      typename: tempProductData1[0].typename,
      description: tempProductData1[0].description,
      image: tempProductData1[0].image
    }
    this.setData({
      showManageClassForm: true,
      showOperationButtons:false,
      tempProductData1: tempProductData1,
      classNavActiveId: 0,
      classInfo: classInfo
    })
  },
  //点击类别导航栏：刷新右侧类别信息
  assoClassInfo: function (e) {
    this.freshClassInfoByIndex(e.currentTarget.dataset.id)
  },
  //右侧信息根据所选数组id实时刷新
  freshClassInfoByIndex: function (clickId) {
    let tempProductData1 = this.data.tempProductData1
    let classInfo = {    //类别信息
      index: clickId,
      id: tempProductData1[clickId].id,
      typename: tempProductData1[clickId].typename,
      description: tempProductData1[clickId].description,
      image: tempProductData1[clickId].image
    }
    this.setData({
      classNavActiveId: clickId,
      classInfo: classInfo
    })
  },
  //【产品类型名称】：输入联动
  bindTypeNameInput: function (e) {
    let classId = this.data.classInfo.id; //当前类别id
    let editValue = e.detail.value; //用户键入的值
    this.updateClassInfoByIndex(classId, 'typename', editValue)
    this.setData({
      tempProductData1: this.data.tempProductData1
    })
  },
  //【产品类别描述】：输入联动
  bindDescriptionInput: function (e) {
    let classId = this.data.classInfo.id; //当前类别id
    let editValue = e.detail.value; //用户键入的值
    this.updateClassInfoByIndex(classId, 'description', editValue)
  },
  //【产品类别调整顺序】：向上移动
  classMoveUp: function () {
    let index = Number(this.data.classInfo.index)
    if (index == 0) {
      wx.showToast({
        title: '已经到顶啦',
        icon: 'none'
      })
    } else {
      let tempArr = this.data.tempProductData1;
      this.swapArray(tempArr, index, index - 1)
      this.setData({
        tempProductData1: tempArr,
        classNavActiveId: index - 1,//tab选中状态
        'classInfo.index': index - 1,
      })
    }
  },
  //【产品类别调整顺序】：向下移动
  classMoveDown: function () {
    let index = Number(this.data.classInfo.index)
    let tempArr = this.data.tempProductData1;
    if (index == tempArr.length - 1) {
      wx.showToast({
        title: '已经到底啦',
        icon: 'none'
      })
    } else {
      this.swapArray(tempArr, index, index + 1)
      this.setData({
        tempProductData1: tempArr,
        classNavActiveId: index + 1,//tab选中状态
        'classInfo.index': index + 1, //类别的数组序列
      })
    }
  },
  //【删除类别】
  deleteClass: function () {
    let that = this;
    let index = Number(that.data.classInfo.index)
    let tempArr = that.data.tempProductData1;
    let unclassifyProduct = that.data.unclassifyProduct;
    wx.showModal({
      title: '警告：当前类别下有[' + tempArr[index].yoghourt.length + ']件商品',
      content: '删除此类别将删除此类别下所有商品',
      cancelText: '取消',
      confirmText: '继续',
      complete: res => {
        if (res.confirm) {
          //将删除类别下的产品转存
          unclassifyProduct = unclassifyProduct.concat(tempArr[index].yoghourt)
          //执行删除
          tempArr.splice(index, 1)

          that.setData({
            unclassifyProduct: unclassifyProduct,
            tempProductData1: tempArr,
          })
          if (tempArr.length > 0) {
            //删除项目后，默认显示首项
            that.freshClassInfoByIndex(0)
          } else {
            //删除后无项目，清空右侧显示
            that.setData({
              classInfo: {    //类别信息
                id: '',
                index: '',
                typename: '',
                description: '',
                image: ''
              }
            })
          }
        }
      }
    })
  },
  //【新增类别】
  addNewClass: function () {
    let tempProductData1 = this.data.tempProductData1;
    //生成新的类别id
    let newId = 0;
    if (tempProductData1.length == 0) {//(1)数组为空
      newId = 1
    } else { //(2)数组非空
      let max = Number(tempProductData1[0].id);
      for (let i = 0; i < tempProductData1.length; i++) {
        if (Number(tempProductData1[i].id) > max) {
          max = Number(tempProductData1[i].id)
        }
      }
      newId = max + 1
    }
    let newclass = {
      id: newId,
      typename: '等待编辑',
      description: '等待编辑',
      image: 'cloud://test-0c3763.11d6-test-0c3763/classIcon/newClass.png',
      yoghourt: []
    }
    tempProductData1 = tempProductData1.concat(newclass)
    console.log(tempProductData1)
    this.setData({
      tempProductData1: tempProductData1,
    })
    this.freshClassInfoByIndex(tempProductData1.length - 1)
  },
  //【修改/上传】类别icon
  chooseImageAndUpload: function (imgName) {
    var that = this;
    let index = Number(this.data.classInfo.index)
    let classId = Number(this.data.classInfo.id)
    let now = Date.now()
    // 让用户选择一张图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: chooseResult => {
        wx.showLoading({
          title: '正在上传...',
        })
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: 'managerUpload/classIcon' + classId + '_' + new Date().getTime() + '.png',
          // 指定要上传的文件的小程序临时文件路径
          filePath: chooseResult.tempFilePaths[0],
          // 成功回调
          success: res => {
            console.log(res)
            let tempProductData1 = that.data.tempProductData1
            let oldFildId = tempProductData1[index].image
            console.log('删除：' + oldFildId)
            //刷新显示新的图片
            tempProductData1[index].image = res.fileID
            that.setData({
              tempProductData1: tempProductData1,
              'classInfo.image': res.fileID
            })
            wx.hideLoading();
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            })
            //删除老的存储照片（只删除管理员上传文件夹中的图片）
            if (oldFildId.indexOf("managerUpload") != -1) {
              wx.cloud.deleteFile({
                fileList: [oldFildId],
                success: res => {
                  // handle success
                  console.log(res.fileList)
                },
                fail: err => {
                  // handle error
                }
              })
            }
          },
          fail: res => {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        })
      },
    })
  },
  //【返回按钮】：隐藏类别管理窗口
  hideManageClassForm: function () {
    this.setData({
      showManageClassForm: false,
      unclassifyProduct: []
    })
  },
  //【保存按钮】保存按钮点击事件
  saveClassChangeClick: function () {
    let that = this;
    this.setData({
      allProductData: that.data.tempProductData1, //将修改后的数据同步
    })
    wx.showToast({
      title: '保存成功',
    })
  },
  //-----------------------------------------通用方法---------------------------------------------

  //●●●●●根据classId修改类别信息数组[tempProductData1]●●●
  updateClassInfoByIndex: function (classId, prototype, value) { //类别代号，属性名，属性值
    let tempProductData1 = this.data.tempProductData1
    for (let i = 0; i < tempProductData1.length; i++) {
      if (tempProductData1[i].id == classId) {
        tempProductData1[i][prototype] = value
        return
      }
    }
  },
  /**
* 数组元素交换位置
* @param {array} arr 数组
* @param {number} index1 添加项目的位置
* @param {number} index2 删除项目的位置
* index1和index2分别是两个数组的索引值，即是两个要交换元素位置的索引值，如1，5就是数组中下标为1和5的两个元素交换位置
*/
  swapArray: function (arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  },
  //**************************************【产品管理】相关事件******************************************* */
  //-----------------------------------------------------------1.上下架 
  //【更改产品上架或者下架】
  onSaleOrNotClick: function (e) {
    let index = e.currentTarget.dataset.index
    let classIndex = this.data.navActiveId;
    let allProductData = this.data.allProductData;

    if (Number(allProductData[classIndex].yoghourt[index].visible) == 0) {
      allProductData[classIndex].yoghourt[index].visible = 1
    } else {
      allProductData[classIndex].yoghourt[index].visible = 0
    }
    this.setData({
      allProductData: allProductData
    })
  },
  //-----------------------------------------------------------2.更改类别
  //【更改类别】：点击更改类别标签
  changeProductClassClick: function (e) {
    let classIndex = this.data.navActiveId
    this.setData({
      showClassOptions: true,//显示产品类别更改窗体
      currentProductIndex: e.currentTarget.dataset.index,//记录当前操作的产品index（yoghourt数组中的index）
      selectedClassTypeName: this.data.allProductData[classIndex].typename
    })
  },
  //【点击类别选项】
  clickClassOptions: function (e) {
    let classIndex = this.data.navActiveId //当前所在class的index
    let newIndex = e.currentTarget.dataset.id //新选择的class的index
    let originClass = this.data.allProductData[classIndex].typename //原来的类别名称
    let newClass = e.currentTarget.dataset.class //新选择的类别名称
    let currentProductIndex = this.data.currentProductIndex //当前产品index

    console.log(originClass, newClass, newIndex)
    this.setData({
      selectedClassTypeName: newClass
    })
    if (originClass != newClass) {
      //用户确定更改了类别
      let allProductData = this.data.allProductData
      //1.记录产品对象
      let temp = allProductData[classIndex].yoghourt[currentProductIndex]
      //2.从原类别中剔除
      allProductData[classIndex].yoghourt.splice(currentProductIndex, 1)
      //3.修改产品对象中的typeid
      temp.typeid = allProductData[newIndex].id
      //4.向新类别中添加
      allProductData[newIndex].yoghourt.unshift(temp)
      this.setData({
        allProductData: allProductData,
        showClassOptions: false
      })
      wx.showToast({
        title: '更改成功',
        icon: 'success',
        duration: 800
      })
    } else {
      wx.showToast({
        title: '当前产品即为此类别',
        icon: 'none',
        duration: 800
      })
    }
  },
  //【取消更改类别】
  cancelChangeClassType: function (e) {
    this.setData({
      showClassOptions: false,//隐藏产品类别更改窗体
      selectedClassTypeName: ''
    })

  },
  //-----------------------------------------------------------3.进入编辑
  //新增产品信息
  addNewProClick: function () {
    let allProductData = this.data.allProductData
    let classIndex = this.data.navActiveId
    let currentProductInfo = {
      id: Date.now(), //新增的产品id：取时间戳
      name: '',
      price: '',
      promotionprice: 0,
      salenum: 0,
      intro: '',
      label: [],
      optiontypeid: '请点击选择',
      bigimage: 'cloud://test-0c3763.11d6-test-0c3763/yoghourtPhoto/暂无图片.jpg',
      smallimage: 'cloud://test-0c3763.11d6-test-0c3763/yoghourtPhoto/暂无图片.jpg',
      typeid: allProductData[classIndex].id,
      visible: 1
    }
    this.setData({
      showProductDetailInfo: true,//显示产品详细信息
      currentProductIndex: -1,//记录当前操作的产品index（yoghourt数组中的index）:新增时赋值为-1.
      currentProductInfo: currentProductInfo
    })
  },
  //【进入编辑】按钮点击
  editProductDetailInfoClick: function (e) {
    let classIndex = this.data.navActiveId
    this.setData({
      showProductDetailInfo: true,//显示产品详细信息
      currentProductIndex: e.currentTarget.dataset.index,//记录当前操作的产品index（yoghourt数组中的index）
      currentProductInfo: this.data.allProductData[classIndex].yoghourt[e.currentTarget.dataset.index]
    })
  },
  //【2.产品名称】：输入联动
  bindProNameInput: function (e) {
    this.setData({
      'currentProductInfo.name': e.detail.value
    })
  },
  //【3.产品原价】：输入联动
  bindProPriceInput: function (e) {
    this.setData({
      'currentProductInfo.price': Number(e.detail.value).toFixed(2) //默认保留两位小数
    })
  },
  //【4.活动价格】：输入联动
  bindProPromotionPriceInput: function (e) {
    this.setData({
      'currentProductInfo.promotionprice': Number(e.detail.value).toFixed(2)//默认保留两位小数
    })
  },
  //【5.产品销量】：输入联动
  bindProSaleNumInput: function (e) {
    this.setData({
      'currentProductInfo.salenum': e.detail.value
    })
  },
  //【6.产品描述】：输入联动
  bindProIntroInput: function (e) {
    this.setData({
      'currentProductInfo.intro': e.detail.value
    })
  },
  //【7.产品标签】：输入联动
  bindProLabelInput: function (e) {

    let labelArr = this.data.currentProductInfo.label

    labelArr[e.currentTarget.dataset.index] = e.detail.value

    this.setData({
      'currentProductInfo.label': labelArr
    })
  },
  //【增加标签】
  addProLabel: function () {
    let labelArr = this.data.currentProductInfo.label
    //console.log(labelArr, labelArr.length)
    if (labelArr.length < 3) { //上限为3个标签
      labelArr.push('') //添加一个空的标签供用户编辑
      this.setData({
        'currentProductInfo.label': labelArr
      })
    } else {
      wx.showToast({
        title: '已达到上限',
        image: '../../images/important.png'
      })
    }
  },
  //【删除标签】
  deleteProLabel: function () {
    let labelArr = this.data.currentProductInfo.label
    //console.log(labelArr, labelArr.length)
    if (labelArr.length > 0) { //上限为3个标签
      labelArr.splice(labelArr.length - 1, 1)
      this.setData({
        'currentProductInfo.label': labelArr
      })
    } else {
      wx.showToast({
        title: '当前产品无标签',
        image: '../../images/important.png'
      })
    }
  },
  //【弹出加料类型选择】
  showChooseOptionsTypeForm: function (e) {

    let idSet = e.currentTarget.dataset.optionid; //获取id集合(如：1,4,5)
    let idSetArr = (idSet+'').split(',')

    let optionsInfo = this.data.optionsInfo
    let len = optionsInfo.length
    let optionsIdArr=[];
    for (let i = 0; i < len;i++){
      let selected=false;
      for (let j = 0; j < idSetArr.length;j++){
        if (idSetArr[j] == optionsInfo[i].id){
          selected=true;
          break;
        }
      }
      optionsIdArr.push({
        id: optionsInfo[i].id,
        typename: optionsInfo[i].typename,
        selected: selected
      })
    }
    this.setData({
      optionsIdArr: optionsIdArr,
      showChooseOptionsType: true, //显示加料类型选择窗口    
    })
  },
  //【加料类型】:点击标签
  changeOptionsType: function (e) {
    let index = e.currentTarget.dataset.index
    let optionsIdArr = this.data.optionsIdArr
    optionsIdArr[index].selected = !optionsIdArr[index].selected

    this.setData({
      optionsIdArr: optionsIdArr,
      //'currentProductInfo.optiontypeid': optionid
    })
  },
  //【加料类型】:确定选择
  confirmChooseOptionsType: function (e) {
    let optionsIdArr = this.data.optionsIdArr
    let tempArr=[];
    for (let i = 0; i < optionsIdArr.length;i++){
      if (optionsIdArr[i].selected){
        tempArr.push(optionsIdArr[i].id)
      }
    }
    this.setData({
      showChooseOptionsType: false,//关闭选择窗口
      optionsIdArr: '', //清空临时选项
      'currentProductInfo.optiontypeid': tempArr.join(',')
    })
  },

  //【加料类型】:取消选择
  cancelChooseOptionsType: function () {
    this.setData({
      showChooseOptionsType: false,//关闭选择窗口
      optionsIdArr: '', //清空临时选项
    })
  },
  //【更改详情大图】
  chooseImageAndUploadForBigImage: function () {
    var that = this;
    let now = Date.now()
    // 让用户选择一张图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: chooseResult => {
        wx.showLoading({
          title: '正在上传...',
        })
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: 'managerUpload/bigImage' + '_' + new Date().getTime() + '.png',
          // 指定要上传的文件的小程序临时文件路径
          filePath: chooseResult.tempFilePaths[0],
          // 成功回调
          success: res => {
            console.log(res)
            //修改当前产品的bigimage
            let currentProductInfo = that.data.currentProductInfo
            let oldFildId = currentProductInfo.bigimage
            console.log('删除：' + oldFildId)
            //刷新显示新的图片
            currentProductInfo.bigimage = res.fileID
            that.setData({
              currentProductInfo: currentProductInfo,
            })
            wx.hideLoading();
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            })
            //删除老的存储照片（只删除管理员上传文件夹中的图片）
            if (oldFildId.indexOf("managerUpload") != -1) {
              wx.cloud.deleteFile({
                fileList: [oldFildId],
                success: res => {
                  // handle success
                  console.log(res.fileList)
                },
                fail: err => {
                  // handle error
                }
              })
            }
          },
          fail: res => {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        })
      },
    })
  },
  //【更改缩略图】
  chooseImageAndUploadForSmallImage: function () {
    var that = this;
    let now = Date.now()
    // 让用户选择一张图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: chooseResult => {
        wx.showLoading({
          title: '正在上传...',
        })
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: 'managerUpload/smallimage' + '_' + new Date().getTime() + '.png',
          // 指定要上传的文件的小程序临时文件路径
          filePath: chooseResult.tempFilePaths[0],
          // 成功回调
          success: res => {
            console.log(res)
            //修改当前产品的bigimage
            let currentProductInfo = that.data.currentProductInfo
            let oldFildId = currentProductInfo.smallimage
            console.log('删除：' + oldFildId)
            //刷新显示新的图片
            currentProductInfo.smallimage = res.fileID
            that.setData({
              currentProductInfo: currentProductInfo,
            })
            wx.hideLoading();
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            })
            //删除老的存储照片（只删除管理员上传文件夹中的图片）
            if (oldFildId.indexOf("managerUpload") != -1) {
              wx.cloud.deleteFile({
                fileList: [oldFildId],
                success: res => {
                  // handle success
                  console.log(res.fileList)
                },
                fail: err => {
                  // handle error
                }
              })
            }
          },
          fail: res => {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        })
      },
    })
  },
  //编辑产品信息【返回】按钮
  cancelEditProductInfo: function () {
    this.setData({
      showProductDetailInfo: false,//显示产品详细信息
      currentProductInfo: {}
    })
  },
  //编辑产品信息【保存】按钮:（1）保存新的产品信息（2）更新原有产品信息
  saveEditProductInfo: function () {
    let classId = this.data.navActiveId;
    let currentProductIndex = this.data.currentProductIndex;
    let currentProductInfo = this.data.currentProductInfo;
    let allProductData = this.data.allProductData

    if (currentProductIndex == -1) { //1.新增产品信息
      allProductData[classId].yoghourt.push(currentProductInfo)
      wx.showToast({
        title: '新增产品至末尾',
        icon: 'none'
      })
    } else { //2.更新产品信息
      allProductData[classId].yoghourt[currentProductIndex] = currentProductInfo
    }
    this.setData({
      allProductData: allProductData,
      showProductDetailInfo: false
    })

  },
  //-----------------------------------------------------------4.向上排序
  //【调整产品顺序】：向上调整
  productMoveUpClick: function (e) {
    let classId = this.data.navActiveId;
    let index = Number(e.currentTarget.dataset.index)
    let allProductData = this.data.allProductData
    if (index == 0) {
      wx.showToast({
        title: '已经到顶啦',
        icon: 'none'
      })
    } else {
      let yoghourt = allProductData[classId].yoghourt;
      this.swapArray(yoghourt, index, index - 1)
      allProductData[classId].yoghourt = yoghourt;
      this.setData({
        allProductData: allProductData,
      })
    }
  },
  //-----------------------------------------------------------5.删除产品
  //【显示删除按钮】：长按单个产品
  showDeleteMaskClick: function () {
    this.setData({
      showDeleteMask: true
    })
  },
  //【隐藏删除按钮】：点击蒙层处
  hideDeleteMaskClick: function () {
    this.setData({
      showDeleteMask: false
    })
  },
  //【删除单个产品】:点击删除按钮
  deleteOneProduct: function (e) {
    let classIndex = this.data.navActiveId;
    let proIndex = e.currentTarget.dataset.id;
    let allProductData = this.data.allProductData;
    allProductData[classIndex].yoghourt.splice(proIndex, 1)
    this.setData({
      allProductData: allProductData
    })
  },
  //【清空当前类别】:点击清空类别
  clearAllProductsOfCurrentClass: function () {
    let classIndex = this.data.navActiveId;
    let allProductData = this.data.allProductData;
    allProductData[classIndex].yoghourt = []
    this.setData({
      allProductData: allProductData,
      showDeleteMask: false
    })
  },
  //**************************************【加料管理】相关事件******************************************* */
  //【显示加料管理窗口】：点击[加料管理]
  showManageOptionsFormClick: function () {
    this.setData({
      showManageOptionsForm: true,
      showOperationButtons: false,
      optionsInfoCopy: this.data.optionsInfo
    })
  },
  //【关联加料管理类别id】：点击[导航栏]
  assoOptionsId: function (e) {
    this.setData({
      optionsNavActiveId: e.currentTarget.dataset.id
    })
  },
  //【选项名称输入联动】
  optionsTypenameBindBlur: function (e) {
    let index = this.data.optionsNavActiveId;
    let optionsInfoCopy = this.data.optionsInfoCopy
    optionsInfoCopy[index].typename = e.detail.value
    this.setData({
      optionsInfoCopy: optionsInfoCopy
    })
  },
  //【选项备注输入联动】
  optionsRemarkBindBlur: function (e) {
    let index = this.data.optionsNavActiveId;
    let optionsInfoCopy = this.data.optionsInfoCopy
    optionsInfoCopy[index].remark = e.detail.value
    this.setData({
      optionsInfoCopy: optionsInfoCopy
    })
  },
  //【更改选项类型】：true：多选/false：单选
  changeOptionSelectType:function(e){
    let multi = e.detail.value;
    let index1 = this.data.optionsNavActiveId;
    let index2 = e.currentTarget.dataset.index2
    let optionsInfoCopy = this.data.optionsInfoCopy
    if (multi){
      optionsInfoCopy[index1].optionData[index2].choose='多选'
    }else{
      optionsInfoCopy[index1].optionData[index2].choose = '单选'
    }
    this.setData({
      optionsInfoCopy: optionsInfoCopy
    })
  },
  //【删除】：删除整个选项大类别
  deleteOneOptions:function(e){
    let index = this.data.optionsNavActiveId;
    let optionsInfoCopy = this.data.optionsInfoCopy
    let optionsId = Number(optionsInfoCopy[index].id)
    //删除大选项组前校验：若当前产品选项列表仍然使用此选项代号，则不允许删除
    let allProductData = this.data.allProductData
    let proNum=0;
    for (let m = 0; m < allProductData.length;m++){
      let yoghourt = allProductData[m].yoghourt
      for (let n = 0; n < yoghourt.length;n++){
        if (Number(yoghourt[n].optiontypeid) == optionsId){
          proNum++;
        }
      }
    }
    if (proNum==0){
      //说明当前选项组，已经没有产品使用，允许删除
      optionsInfoCopy.splice(index, 1)
      this.setData({
        optionsInfoCopy: optionsInfoCopy,
        optionsNavActiveId:0
      })
      wx.showToast({
        title: '删除成功',
      })
    }else{
      wx.showModal({
        title: '无法删除',
        content: '当前有[' + proNum+']个产品正在使用此选项配置',
        showCancel:false
      })
    }
  },
  //【移动整个类别】:上移调整整个类别
  moveUpOneTypeOption:function(e){
    let index1 = this.data.optionsNavActiveId;
    let index2 = e.currentTarget.dataset.index2
    let optionsInfoCopy = this.data.optionsInfoCopy

    if (index2 == 0) {
      wx.showToast({
        title: '已经到顶啦',
        icon: 'none'
      })
    } else {
      let tempArr = optionsInfoCopy[index1].optionData
      this.swapArray(tempArr, index2, index2 - 1)
      this.setData({
        optionsInfoCopy: optionsInfoCopy
      })
    }
  },
  //【输入联动】:选项类别名称 type
  optionsTypeBindBlur:function(e){
    let index = this.data.optionsNavActiveId;
    let optionsInfoCopy = this.data.optionsInfoCopy
    optionsInfoCopy[index].optionData[e.currentTarget.dataset.index].type = e.detail.value
    this.setData({
      optionsInfoCopy: optionsInfoCopy
    })
  },
  //【删除】：删除一种type类型
  deleteOneTypeOptions:function(e){
    wx.showModal({
      title: '确认删除此类别？',
      content: '若误删除后请勿点击保存，取消后重新进入',
      confirmText:'继续',
      complete:res=>{
        if(res.confirm){
          let index = this.data.optionsNavActiveId;
          let optionsInfoCopy = this.data.optionsInfoCopy
          optionsInfoCopy[index].optionData.splice(e.currentTarget.dataset.index, 1)
          this.setData({
            optionsInfoCopy: optionsInfoCopy,
          })
        }
      }
      
    })
  },
  //【输入联动】:选项标签名称 name
  optionsLableNameBindBlur: function (e) {
    let index1 = this.data.optionsNavActiveId; //1.选项大类别
    let index2 = e.currentTarget.dataset.index2 //2.选项二级类别（小酸酸）
    let index3 = e.currentTarget.dataset.index3 //3.选项标签下标
    let optionsInfoCopy = this.data.optionsInfoCopy
    optionsInfoCopy[index1].optionData[index2].optionlistData[index3].name = e.detail.value
    this.setData({
      optionsInfoCopy: optionsInfoCopy
    })
  },
  //【输入联动】:选项标价格 price
  optionsLablePriceBindBlur: function (e) {
    let index1 = this.data.optionsNavActiveId; //1.选项大类别
    let index2 = e.currentTarget.dataset.index2 //2.选项二级类别（小酸酸）
    let index3 = e.currentTarget.dataset.index3 //3.选项标签下标
    let optionsInfoCopy = this.data.optionsInfoCopy
    optionsInfoCopy[index1].optionData[index2].optionlistData[index3].price = Number(e.detail.value).toFixed(2)
    this.setData({
      optionsInfoCopy: optionsInfoCopy
    })
  },
  //【长按】显示加料标签的操作按钮
  showLabelOperationButtonsClick:function(){
    this.setData({
      showLabelOperationButtons:true
    })
  },
  //【隐藏】点击隐藏加料标签的操作按钮
  hideLabelOperationButtonsClick: function () {
    this.setData({
      showLabelOperationButtons: false
    })
  },
  //【添加选项】点击
  addNewOptionLabel:function(e){
    let index1 = this.data.optionsNavActiveId; //1.选项大类别
    let index2 = e.currentTarget.dataset.index2 //2.选项二级类别（小酸酸）
    let optionsInfoCopy = this.data.optionsInfoCopy
    //确定新增label的id
    let tempArr = optionsInfoCopy[index1].optionData
    let maxId=0
    for (let m = 0; m < tempArr.length;m++)
    {
      for (let n = 0; n < tempArr[m].optionlistData.length;n++)
      {
        let listid = Number(tempArr[m].optionlistData[n].listid)
        if (listid > maxId)
        {
          maxId = listid
        }
      }
    }
    let newLabel={
      listid: maxId+1,
      name:'',
      price:'',
      selected:''
    }
    //向此数组中新增
    optionsInfoCopy[index1].optionData[index2].optionlistData.push(newLabel)
    this.setData({
      optionsInfoCopy: optionsInfoCopy
    })
  },
  //【向上移动】：操作按钮
  labelMoveUpButtonClick:function(e){
    let index1 = this.data.optionsNavActiveId; //1.选项大类别
    let index2 = e.currentTarget.dataset.index2 //2.选项二级类别（小酸酸）
    let index3 = e.currentTarget.dataset.index3 //3.选项标签下标
    let optionsInfoCopy = this.data.optionsInfoCopy

    if (index3 == 0) {
      wx.showToast({
        title: '已经到顶啦',
        icon: 'none'
      })
    } else {
      let tempArr = optionsInfoCopy[index1].optionData[index2].optionlistData
      this.swapArray(tempArr, index3, index3 - 1)

      this.setData({
        optionsInfoCopy: optionsInfoCopy
      })
    }
  },
  //【移出此组】：操作按钮
  labelMoveOutButtonClick:function(e){
    let index1 = this.data.optionsNavActiveId; //1.选项大类别
    let index2 = e.currentTarget.dataset.index2 //2.选项二级类别（小酸酸）
    let index3 = e.currentTarget.dataset.index3 //3.选项标签下标
    let optionsInfoCopy = this.data.optionsInfoCopy
    let itemList=[];
    let newIndex2=0;
    for (let i = 0; i < optionsInfoCopy[index1].optionData.length;i++)
    {
      itemList.push(optionsInfoCopy[index1].optionData[i].type)
    }
    wx.showActionSheet({
      itemList: itemList ,
      success:res=>{
        newIndex2=res.tapIndex;
        if (index2 == newIndex2)
        {
          wx.showToast({
            title: '当前即为此类别',
            icon:'none'
          })
          return;
        }else{ //移动至新的类别
          let labelItem = optionsInfoCopy[index1].optionData[index2].optionlistData[index3]
          //删除原类别
          optionsInfoCopy[index1].optionData[index2].optionlistData.splice(index3,1)
          //向待移动组中添加
          optionsInfoCopy[index1].optionData[newIndex2].optionlistData.push(labelItem)
          //刷新显示
          this.setData({
            optionsInfoCopy: optionsInfoCopy
          })
        }
      }
    })
  },
  //【删除选项标签】：操作按钮
  labelDeleteButtonClick:function(e){
    let index1 = this.data.optionsNavActiveId; //1.选项大类别
    let index2 = e.currentTarget.dataset.index2 //2.选项二级类别（小酸酸）
    let index3 = e.currentTarget.dataset.index3 //3.选项标签下标
    let optionsInfoCopy = this.data.optionsInfoCopy
    optionsInfoCopy[index1].optionData[index2].optionlistData.splice(index3, 1)
    //刷新显示
    this.setData({
      optionsInfoCopy: optionsInfoCopy
    })
  },
  //【添加小类别】：点击事件
  addNewTypeOptionClick:function(e){
    let index = this.data.optionsNavActiveId;
    let optionsInfoCopy = this.data.optionsInfoCopy
    let optionDataObj={
      choose:'多选',
      optionlistData:[],
      type:''
    }
    optionsInfoCopy[index].optionData.push(optionDataObj)
    this.setData({
      optionsInfoCopy: optionsInfoCopy,
    })

  },
  //【添加大选项组】
  addGroupOptionsClick:function(e){
    let optionsInfoCopy = this.data.optionsInfoCopy 
    //新增选项组获取id
    let maxId=0;
    for (let i = 0; i < optionsInfoCopy.length;i++){
      let id = Number(optionsInfoCopy[i].id)
      if (id > maxId){
        maxId=id
      }
    }
    //确定新增对象
    let optionsInfoCopyObj={
      id: maxId+1,
      typename:'未命名',
      remark:'',
      optionData:[]
    }
    //向数组中新增对象
    optionsInfoCopy.push(optionsInfoCopyObj)
    //同步数据
    this.setData({
      optionsInfoCopy: optionsInfoCopy,
      optionsNavActiveId: optionsInfoCopy.length-1
    })

  },
  //【返回按钮】：返回编辑选项数据
  cancelEditOptionData:function(){
    this.setData({
      showManageOptionsForm: false,
      optionsInfoCopy:[]
    })
  },
  //【保存按钮】：保存当前编辑选项数据
  saveOptionsChangeClick:function(){
    console.log(this.data.optionsInfoCopy)
    this.setData({
      optionsInfo: this.data.optionsInfoCopy, //将修改后的数据同步
      //showManageOptionsForm: false, //隐藏编辑窗体
    })
    wx.showToast({
      title: '保存成功',
    })
  },
//**************************************【同步数据】相关事件******************************************* */
updateProductInfo:function(){

  let that=this;
  wx.showModal({
    title: '此操作不可逆',
    content: '确认继续同步数据至服务器吗？',
    cancelText:'我再想想',
    confirmText:'继续同步',
    complete:res=>{
      if(res.confirm){
        that.startUpdateProductInfo()
      }
    }
  })
},
//同步数据子程序
startUpdateProductInfo:function(){
  //console.log('同步数据中...')
  let that=this
  wx.showLoading({
    title: '正在同步...'
  })
  wx.cloud.callFunction({
    name: 'updateProductInfo',
    data: {
      optionsInfo: that.data.optionsInfo,
      productInfo: that.data.allProductData
    }
  }).then(res => {
    wx.hideLoading() //关闭加载
    if (res.result.result == 'success') {
      //(1)清空当前产品数据
      try {
        getApp().globalData.productInfo = that.data.allProductData
        getApp().globalData.optionsInfo = that.data.optionsInfo
        wx.cloud.callFunction({
          name: 'getData',
          data: {
            optionsInfo: that.data.optionsInfo,
            productInfo: that.data.allProductData
          }
        }).then(res => {
          wx.hideLoading() //关闭加载
          wx.showToast({
            title: '同步成功',
          })
        })
      }
      catch (e) {
      }
    }
    else {
      wx.hideLoading() //关闭加载
      wx.showModal({
        title: '友情提示',
        content: '同步失败，请检查网络状态后再试',
        showCancel: false
      })
    }
  }).catch(res => {
    wx.hideLoading() //关闭加载
    wx.showModal({
      title: '友情提示',
      content: '同步失败，请检查网络状态后再试',
      showCancel: false
    })
  })
},
})

